package com.sykj.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sykj.model.User;
import com.sykj.service.UserService;

@Component("shiroRealm")
public class ShiroRealm extends AuthenticatingRealm {
	
	@Autowired
	UserService loginService;
	
	/**
	 * 登录认证方法，执行登录后返回认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token){
		UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
		User user = loginService.getUser(uptoken.getUsername());	
		SimpleAuthenticationInfo info;
		if(user!=null){
			Object principal=uptoken.getUsername();
			System.out.println("密码" + user.getPassword());
			Object credentials= user.getPassword();//user.getPassword();
			String realmName = getName();
			ByteSource salt = ByteSource.Util.bytes(principal);//用户名获得盐值
			info = new SimpleAuthenticationInfo(principal, credentials, salt, realmName);	
		}else{
			System.out.println("UnknownAccountException");
			throw new UnknownAccountException("用户不存在");
		}
		return info;


	}

}
